# coding: utf-8

import os

import config
import http as httpHandler
import jsonp as jsonHanlder

from initialize import logger


class CookieHandler(object):

    def __init__(self, domain=None):
        self.cookie_file = config.COOKIE_FILE
        self.domain = domain

    def __read(self):
        if not os.path.exists(self.cookie_file):
            return None
        with open(self.cookie_file, 'r') as file:
            return file.read()

    def __write(self, string):
        with open(self.cookie_file, 'w+') as file:
            file.write(string)

    def get_cookie_to_string(self, cookie_name):
        string = self.__read()
        if string:
            try:
                dic = jsonHanlder.to_object(string)
                if dic.has_key(cookie_name):
                    return dic[cookie_name]
            except Exception as e:
                logger.error(e)
        return None

    def get_cookie_to_list(self, cookie_name):
        cookie_string = self.get_cookie_to_string(cookie_name)
        return self.string_to_list(cookie_string)

    def get_cookie_to_dict(self, cookie_name):
        cookies = self.get_cookie_to_list(cookie_name)
        return httpHandler.get_requests_cookie(cookies)

    def set_cookie_string(self, cookie_name, cookie_string):
        dic = None
        string = self.__read()
        if string:
            try:
                dic = jsonHanlder.to_object(string)
            except Exception as e:
                logger.error(e)
        if dic is None:
            dic = dict()
        dic[cookie_name] = cookie_string
        string = jsonHanlder.to_json(dic)
        self.__write(string)

    def set_cookie_list(self, cookie_name, cookie_list):
        cookie_string = ''
        for cookie_dict in cookie_list:
            cookie_string += '{0}={1}; '.format(cookie_dict['name'], cookie_dict['value'])
        self.set_cookie_string(cookie_name, cookie_string)

    def string_to_list(self, cookie_string):
        cookies = []
        if cookie_string is None or cookie_string == '':
            return cookies
        cookie_array = cookie_string.split('; ')
        for cookie_dic_string in cookie_array:
            if cookie_dic_string == '':
                continue
            cookie_dic_array = cookie_dic_string.split('=')
            cookie = {}
            cookie['name'] = cookie_dic_array[0]
            cookie['value'] = cookie_dic_array[1]
            # if cookie_dic_array[1] == 'true':
            #     cookie['value'] = True
            # elif cookie_dic_array[1] == 'false':
            #     cookie['value'] = False
            # else:
            #     cookie['value'] = cookie_dic_array[1]
            cookie['path'] = '/'
            cookie['domain'] = self.domain
            cookie['secure'] = False
            cookie['httpOnly'] = True
            cookie['expires'] = None
            cookies.append(cookie)
        return cookies

    def tuples_to_list(self, tuples):
        cookies = []
        for tuple in tuples:
            cookie = {}
            cookie['name'] = tuple[0]
            cookie['value'] = tuple[1]
            cookie['path'] = '/'
            cookie['domain'] = self.domain
            cookie['secure'] = False
            cookie['httpOnly'] = True
            cookie['expires'] = None
            cookies.append(cookie)
        return cookies

    def list_to_string(self, cookies):
        cookie_string = ''
        for cookie in cookies:
            cookie_string += '{0}={1}; '.format(cookie['name'], cookie['value'])
        return cookie_string
